package cn.wolfcode.business.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.wolfcode.business.domain.BpmnInfo;
import cn.wolfcode.business.domain.CarPackageAudit;
import cn.wolfcode.business.mapper.BpmnInfoMapper;
import cn.wolfcode.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.business.vo.AuditInfoVO;
import cn.wolfcode.business.vo.AuditVO;
import cn.wolfcode.common.core.domain.entity.SysUser;
import cn.wolfcode.common.exception.ServiceException;
import cn.wolfcode.common.utils.DateUtils;
import cn.wolfcode.common.utils.SecurityUtils;
import cn.wolfcode.system.mapper.SysConfigMapper;
import cn.wolfcode.system.mapper.SysUserMapper;
import cn.wolfcode.system.service.ISysConfigService;
import cn.wolfcode.system.service.impl.SysConfigServiceImpl;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcode.business.mapper.ServiceItemMapper;
import cn.wolfcode.business.domain.ServiceItem;
import cn.wolfcode.business.service.IServiceItemService;

/**
 * 服务项Service业务层处理
 * 
 * @author dafei
 * @date 2024-03-02
 */
@Service
public class ServiceItemServiceImpl implements IServiceItemService 
{
    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    /**
     * 查询服务项
     * 
     * @param id 服务项主键
     * @return 服务项
     */
    @Override
    public ServiceItem selectServiceItemById(Long id)
    {
        return serviceItemMapper.selectServiceItemById(id);
    }

    /**
     * 查询服务项列表
     * 
     * @param serviceItem 服务项
     * @return 服务项
     */
    @Override
    public List<ServiceItem> selectServiceItemList(ServiceItem serviceItem)
    {
        return serviceItemMapper.selectServiceItemList(serviceItem);
    }

    /**
     * 新增服务项
     * 
     * @param serviceItem 服务项
     * @return 结果
     */
    @Override
    public int insertServiceItem(ServiceItem serviceItem)
    {
        //参数判断是否为null --- @TODO
        //原价  折扣价必须大于0 --- @TODO

        //原价 必须大于等于 折扣价
        if(serviceItem.getOriginalPrice().compareTo(serviceItem.getDiscountPrice()) < 0){
            throw new ServiceException("原价必须大于或等于折扣价");
        }

        //是否套餐--- 是：审核状态-初始化   否：审核状态-无需审核

        if(serviceItem.getCarPackage() == ServiceItem.CARPACKAGE_NO){
            //非套餐-无需审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }else{
            //套餐-初始化
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }

        //上架状态：下架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);


        serviceItem.setCreateTime(DateUtils.getNowDate());
        return serviceItemMapper.insertServiceItem(serviceItem);
    }

    /**
     * 修改服务项
     * 
     * @param serviceItem 服务项
     * @return 结果
     */
    @Override
    public int updateServiceItem(ServiceItem serviceItem)
    {

        //参数判断是否为null --- @TODO
        //原价  折扣价必须大于0 --- @TODO
        ServiceItem item = serviceItemMapper.selectServiceItemById(serviceItem.getId());

        if(item == null){
            throw new ServiceException("参数异常");
        }

        //原价 必须大于等于 折扣价
        if(serviceItem.getOriginalPrice().compareTo(serviceItem.getDiscountPrice()) < 0){
            throw new ServiceException("原价必须大于或等于折扣价");
        }
        //不允许修改是否套餐状态
        if(item.getCarPackage() != serviceItem.getCarPackage()){
            throw new ServiceException("不允许修改套餐状态");
        }


        //如果是套餐---审核中--不允许修改
        if(item.getCarPackage() == ServiceItem.CARPACKAGE_YES){
            if(item.getAuditStatus() == ServiceItem.AUDITSTATUS_AUDITING){
                throw new ServiceException("审核中套餐不允许修改");
            }
        }

        //上架 不允许修改
        if(item.getSaleStatus() == ServiceItem.SALESTATUS_ON){
            throw new ServiceException("服务项/套餐上架后不允许修改");
        }

        return serviceItemMapper.updateServiceItem(serviceItem);
    }

    /**
     * 批量删除服务项
     * 
     * @param ids 需要删除的服务项主键
     * @return 结果
     */
    @Override
    public int deleteServiceItemByIds(Long[] ids)
    {
        return serviceItemMapper.deleteServiceItemByIds(ids);
    }

    /**
     * 删除服务项信息
     * 
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int deleteServiceItemById(Long id)
    {
        return serviceItemMapper.deleteServiceItemById(id);
    }

    @Override
    public void saleOn(Long id) {

        //条件
        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(id);
        if(serviceItem == null){
            throw new ServiceException("参数异常");
        }

    /*    if(serviceItem.getCarPackage() == ServiceItem.CARPACKAGE_NO){
            //非套餐---非上架
            if(serviceItem.getSaleStatus() == ServiceItem.SALESTATUS_ON){
                throw new ServiceException("非套餐非下架状态不允许执行上架操作");
            }
        }else{
            //套餐---审核通过---非上架
            if(serviceItem.getAuditStatus() != ServiceItem.AUDITSTATUS_APPROVED){
                throw new ServiceException("套餐必须在审核通过才允许上架");
            }

            if(serviceItem.getSaleStatus() == ServiceItem.SALESTATUS_ON){
                throw new ServiceException("套餐非下架状态不允许执行上架操作");
            }
        }*/


        if (serviceItem.getCarPackage() == ServiceItem.CARPACKAGE_YES){
            if(serviceItem.getAuditStatus() != ServiceItem.AUDITSTATUS_APPROVED){
                throw new ServiceException("套餐必须在审核通过才允许上架");
            }
        }
        if(serviceItem.getSaleStatus() == ServiceItem.SALESTATUS_ON){
            throw new ServiceException("服务项/套餐非下架状态不允许执行上架操作");
        }

        //修改--状态：上架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_ON);
        serviceItemMapper.updateServiceItem(serviceItem);
    }

    @Override
    public void saleOff(Long id) {
        //条件
        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(id);
        if(serviceItem == null){
            throw new ServiceException("参数异常");
        }
        //修改--状态：下架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItemMapper.updateServiceItem(serviceItem);
    }

    @Override
    public AuditInfoVO getAuditInfo(Long id) {
        //1: serviceItem

        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(id);
        //服务套餐
        //2: BpmnInfo
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectByKey("bus_car_package");
        //5: 是否需要财务审核价格限制：3000  --- 不建议直接写死---:
        // 1>方式1：配置文件
        // 2>方式2：设计一个参数配置表--直接改动配置参数，从而影响获取的数据
        String limit = sysConfigService.selectConfigByKey("discountPriceLimit");

        //3: 店长-用户列表
        List<SysUser>  shopOwners  = sysUserMapper.selectByRoleKey("shopOwner");
        //4: 财务-用户列表
        List<SysUser>  finances  =  sysUserMapper.selectByRoleKey("finance");;


        AuditInfoVO vo = new AuditInfoVO();
        vo.setServiceItem(serviceItem);
        vo.setBpmnInfo(bpmnInfo);
        vo.setDiscountPrice(new BigDecimal(limit));
        vo.setFinances(finances);
        vo.setShopOwners(shopOwners);

        return vo;
    }

    @Override
    public void startAudit(AuditVO vo) {

        //条件
        ServiceItem serviceItem = serviceItemMapper.selectServiceItemById(vo.getServiceItemId());
        if(serviceItem == null){
            throw new ServiceException("参数异常");
        }

        if(serviceItem.getCarPackage() != ServiceItem.CARPACKAGE_YES){
            throw new ServiceException("必须是服务套餐才允许审核");
        }

        if(serviceItem.getAuditStatus() != ServiceItem.AUDITSTATUS_INIT){
            throw new ServiceException("服务套餐必须是初始化状态才允许审核");
        }

        if(serviceItem.getSaleStatus() != ServiceItem.SALESTATUS_OFF){
            throw new ServiceException("服务套餐必须是下架状态才允许审核");
        }

        //改数据--
        // 套餐服务状态--审核中
        serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_AUDITING);
        serviceItemMapper.updateServiceItem(serviceItem);

        // 套餐审核记录表--添加记录
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(vo.getServiceItemId());
        audit.setInfo(vo.getInfo());
        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
        audit.setServiceItemName(serviceItem.getName());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setCreatorId(SecurityUtils.getUserId().toString());
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setCreateTime(new Date());

        carPackageAuditMapper.insertCarPackageAudit(audit);
        // 启动流程
        String businessKey = audit.getId().toString();
        Map<String, Object> variables = new HashMap<>();
        if(vo.getShopOwnerId() != null){
            variables.put("shopOwnerId", vo.getShopOwnerId());
        }
        if(vo.getFinanceId() != null){
            variables.put("financeId", vo.getFinanceId());
        }
        variables.put("disCountPrice", serviceItem.getDiscountPrice().longValue());
        BpmnInfo bpmnInfo = bpmnInfoMapper. selectByType(CarPackageAudit.FLOW_AUDIT_TYPE);
        //参数1：审核流程定义key， 参数2：业务标识key  参数3：流程图设置变量
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(bpmnInfo.getProcessDefinitionKey(), businessKey, variables);


        audit.setInstanceId(processInstance.getProcessInstanceId());  //流程实例
        carPackageAuditMapper.updateCarPackageAudit(audit);

    }
}
